<template>
<div></div>
</template>
<script>
import { IMEVENTNAME } from '../tool/imEvent';
export default {
	name: 'CcsIm',
	props: {
		// ccsUrl:{
		//     type:String,
		//     required:true
		// },
		// token:{
		//     type:String,
		//     required:true
		// },
	},
	data() {
		return {
			ccsIMClient: null,
			isFirstConnectedSuccess: false, //第一次连接成功
			ticket: null,
			ccsTicketInterval: null //ticket刷新定时器
		};
	},
	methods: {
		initConnectCCS(ccsUrl, token, isTokenExpired) {
			// eslint-disable-next-line no-undef
			this.ccsIMClient = new ccsClient();
			this.ccsIMClient.connect(ccsUrl, token, () => {
				isTokenExpired();
			});
			this.onConnect();
			this.onDisconnect();
		},
		onDisconnect() {
			var self = this;
			this.ccsIMClient.onDisconnect(function(reason) {
				self.$bus.emit(IMEVENTNAME.disconnected, 'socket disconnect ' + reason);
			});
			this.ccsIMClient.onReconnectFailed(function(reason) {
				self.$bus.emit(IMEVENTNAME.disconnected, 'ccs socketio reconnect failed ' + reason);
			});
		},
		onConnect() {
			var self = this;
			this.ccsIMClient.onConnect(function() {
				console.log('ccs connected at', new Date());
				if (self.isFirstConnectedSuccess) {
					//非第一次重连成功,需要刷新connect
					self.resumeConnection();
				} else {
					self.businessListener();
					self.isFirstConnectedSuccess = true;
				}
			});
		},
		resumeConnection() {
			return new Promise((resolve, reject) => {
				if (this.ticket == null) {
					reject('ticket is null');
				} else {
					var self = this;
					this.ccsIMClient.resumeConnection(this.ticket, function(status, resp) {
						if (status === 'ok') {
							console.log('resume Connection success.', JSON.stringify(resp));
							self.ticket = resp.ticket;
						} else {
							self.$bus.emit(IMEVENTNAME.resumeConnectionFailed, 'resume connect failed ' + resp); //重连失败-->业务操作提示
						}
					});
				}
			});
		},

		refreshTicket() {
			var self = this;
			if (this.ccsIMClient) {
				this.ccsIMClient.refreshTicket(function(status, resp) {
					if (status === 'ok') {
						self.ticket = resp.ticket;
						console.log('refreshTicket success,new ticket=', self.ticket);
					} else {
						self.$bus.emit(IMEVENTNAME.refreshTicketFailed, 'refresh ticket failed ' + resp);
					}
				});
			}
		},

		sendHandWritingMessage(message) {
			return new Promise((resolve, reject) => {
				this.ccsIMClient.sendHandwritingMessage(message, 'agents', function(status, resp, msgId) {
					console.log('sendHandwritingMessage result', status);
					console.log('sendHandwritingMessage msgId', msgId);
					if (status === 'ok') {
						resolve(msgId);
					} else {
						reject(resp);
					}
				});
			});
		},

		requestSession(data) {
			console.log('client request session data:', data);
			return new Promise((resolve, reject) => {
				var self = this;
				this.ccsIMClient.requestSession(data, function(status, resp) {
					console.log('request session', resp, status);
					self.$bus.emit(IMEVENTNAME.receiveClientId, resp);
					if (status === 'ok') {
						var ccs_ticket_refreshtime = resp.refershTicketTime;
						self.ticket = resp.ticket;
						if (self.ccsTicketInterval == null) {
							self.ccsTicketInterval = setInterval(function() {
								self.refreshTicket();
							}, ccs_ticket_refreshtime);
						}
						resolve(resp);
					} else {
						reject(resp);
					}
				});
			});
		},

		quitSession() {
			return new Promise((resolve, reject) => {
				var self = this;
				this.ccsIMClient.quitSession(
					{
						reason: ''
					},
					function(status, resp) {
						if (status === 'ok') {
							clearInterval(self.ccsTicketInterval);
							self.ccsTicketInterval = null;
							self.ticket = null;
							self.isFirstConnectedSuccess = false;
							self.ccsIMClient = null;
							resolve(resp);
						} else {
							reject(resp);
						}
					}
				);
			});
		},

		sendMessageToOther(message) {
			return new Promise((resolve, reject) => {
				this.ccsIMClient.sendTextMessage(message, 'agents', function(status, resp, msgId) {
					if (status === 'ok') {
						console.log('sendMessage Succeed!', resp);
						console.log('msgId=', msgId);
						resolve(msgId);
					} else {
						reject(resp);
					}
				});
			});
		},

		sendMessageConfirmation(message) {
			return new Promise((resolve, reject) => {
				this.ccsIMClient.sendMessageConfirmation(message, 'agents', function(status, resp, msgId) {
					if (status === 'ok') {
						console.log('sendMessage Succeed!', resp);
						console.log('msgId=', msgId);
						resolve(msgId);
					} else {
						reject(resp);
					}
				});
			});
		},

		readyToTalk(selfId, user) {
			return new Promise((resolve, reject) => {
				this.ccsIMClient.readyToTalk(selfId, user, 'agents', function(status, resp, msgId) {
					if (status === 'ok') {
						console.log('sendMessage Succeed!', resp);
						console.log('msgId=', msgId);
						resolve(msgId);
					} else {
						reject(resp);
					}
				});
			});
		},

		sendImageToOther(imageUrl, imageName) {
			return new Promise((resolve, reject) => {
				this.ccsIMClient.shareResource(imageUrl, 'pic', imageName, 'agents', function(status, resp, msgId) {
					if (status === 'ok') {
						console.log('send pic Message Succeed!', resp);
						console.log('send pic Message msgId', msgId);
						resolve(msgId);
					} else {
						reject(resp);
					}
				});
			});
		},

		sendFileToOther(fileUrl, fileName) {
			return new Promise((resolve, reject) => {
				this.ccsIMClient.shareResource(fileUrl, 'doc', fileName, 'agents', function(status, resp, msgId) {
					if (status === 'ok') {
						console.log('send file Message Succeed!', resp);
						console.log('send file Message msgId', msgId);
						resolve(msgId);
					} else {
						reject(resp);
					}
				});
			});
		},

		businessListener() {
			console.log('businessListener();', new Date());
			var self = this;
			this.ccsIMClient.onReadyToTalk(function(resp) {
				console.log('agent is onReadyToTalk', resp, new Date());
				self.$bus.emit(IMEVENTNAME.onReadyToTalk);
			});
			this.ccsIMClient.onQuitSession(function(resp) {
				console.log('agent quitSession:', resp);
				console.log('quit session agent Id,', resp.data.id);
				self.$bus.emit(IMEVENTNAME.onQuitSession, resp);
			});
			this.ccsIMClient.onFormData(function(resp) {
				console.log('onFormData,', resp);
				if (resp.data.inputform === 1) {
					//坐席发送表单，让访客填写提交表单,目前根据不同的技能组坐席发送不同的表单。
					self.$bus.emit(IMEVENTNAME.inviteInputForm, resp.data.formTemplate);
				} else if (resp.data.collect === 1) {
					//坐席发送确认信息，请访客这边确认
					self.$bus.emit(IMEVENTNAME.inviteMakeSureFormInfo, resp.data);
				}
			});
			this.ccsIMClient.onHoldOn(function() {
				console.log('onholdon');
				self.$bus.emit(IMEVENTNAME.onHoldOn);
			});

			this.ccsIMClient.onPhotoGuideBox(function() {
				console.log('receive onPhotoGuideBox');
				self.$bus.emit(IMEVENTNAME.onPhotoGuideBox);
			});

			this.ccsIMClient.onScreenSnapshot(function() {
				console.log('receive onScreenSnapshot');
				self.$bus.emit(IMEVENTNAME.onScreenSnapshot);
			});

			this.ccsIMClient.onTextMessage(function(data) {
				console.log('onTextMessage,', data);
				var message = data.data;
				if (message == 'please handsign') {
					//手写签名
					self.$bus.emit(IMEVENTNAME.handsign);
				} else if (message.indexOf('agentcollectionPic=') != -1) {
					//坐席采集访客的照片，截图
					self.$bus.emit(IMEVENTNAME.collectPic, message);
				} else {
					//接收文字消息
					self.$bus.emit(IMEVENTNAME.receiveMessage, message);
				}
				self.$bus.emit(IMEVENTNAME.receiveMessageData, data);
			});
			// eslint-disable-next-line no-unused-vars
			this.ccsIMClient.onHandwritingMessage(resp => {
				this.$bus.emit(IMEVENTNAME.handsign);
			});

			this.ccsIMClient.onSharedResource(function(resp) {
				console.log('onSharedResource,', resp);
				self.$bus.emit(IMEVENTNAME.onSharedResource, resp);
			});

			this.ccsIMClient.onAck(function(resp) {
				console.log('onAck:', resp);
				self.$bus.emit(IMEVENTNAME.onAck);
			});

			this.ccsIMClient.onDrop(function(resp) {
				console.log('onDrop,', resp);
				self.$bus.emit(IMEVENTNAME.onDrop);
			});

			this.ccsIMClient.onJoinedSession(function(resp) {
				console.log('onJoinedSession:', resp);
				self.$bus.emit(IMEVENTNAME.onJoinedSession, resp);
			});

			this.ccsIMClient.onInvitationProgress(function(resp) {
				console.log('onInvitationProgress,', resp);
				self.$bus.emit(IMEVENTNAME.onInvitationProgress, resp);
			});

			this.ccsIMClient.onCustomMessage(data => {
				self.$bus.emit(IMEVENTNAME.onCustomMessage, data);
			});
		}
	}
};
</script>
